import cv2 as cv
import numpy as np

filename = r'vtest.avi'

#角点检测参数
feature_params = dict( maxCorners = 100, qualityLevel = 0.3, minDistance = 7, blockSize = 7 )
#LK光流法参数
lk_params = dict( winSize = (15,15), maxLevel = 2, criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT,10,0.03) )

capvideo = cv.VideoCapture(filename)
ret,prev = capvideo.read()
pregray = cv.cvtColor(prev,cv.COLOR_BGR2GRAY)
p0 = cv.goodFeaturesToTrack(pregray,mask=None,**feature_params)

while True:
    ret,frame = capvideo.read()
    if not ret: #没有新帧，退出
        break

    gray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)

    #计算光流
    p1, st, err = cv.calcOpticalFlowPyrLK(pregray, gray, p0, None, **lk_params)

    #选取好的跟踪点
    goodPoints = p1[st==1]
    goodprePoint = p0[st==1]

    res = frame.copy()
    drawColor = (0,0,255)

    for i, (cur,prev) in enumerate(zip(goodPoints,goodprePoint)):
        x0,y0 = cur.ravel()
        x1,y1 = prev.ravel()
        cv.line(res,(x0,y0),(x1,y1),drawColor)
        cv.circle(res,(x0,y0),3,drawColor)

    #更新上一帧
    pregray = gray.copy()
    p0 = goodPoints.reshape(-1,1,2)

    cv.imshow('检测结果',res)

    key = cv.waitKey(30)
    if key == 27 :
        break




cv.waitKey()
cv.destroyAllWindows()